﻿using Shop.Model.DB;
using Shop.RemoteModel.CouponGoods.Model;
using Shop.Repository;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;

namespace Shop.Collect.lmpl
{
    internal class CouponGoodsCollect : ICouponGoodsCollect
    {
        private readonly ICouponGoodsRepository _Repository;

        public CouponGoodsCollect (ICouponGoodsRepository repository)
        {
            this._Repository = repository;
        }

        public DBShopCouponGoods[] Adds (long couponId, CoupGoods[] goods)
        {
            DBShopCouponGoods[] datas = this._Repository.GetsByCouponId<DBShopCouponGoods>(couponId);
            if (datas.IsNull())
            {
                return this._Repository.Adds(couponId, goods);
            }
            DBShopCouponGoods[] adds = goods.Convert(a => !datas.IsExists(c => c.SkuId == a.SkuId), a => new DBShopCouponGoods
            {
                CouponId = couponId,
                GoodsId = a.GoodsId,
                SkuId = a.SkuId,
                Id = IdentityHelper.CreateId()
            });
            long[] dropId = datas.Convert(a => !goods.IsExists(c => c.SkuId == a.SkuId), a => a.Id);
            if (adds.IsNull() && dropId.IsNull())
            {
                return datas;
            }
            int num = datas.Length + adds.Length - dropId.Length;
            this._Repository.Sync(adds, dropId, couponId, num);
            datas = datas.FindAll(c => !dropId.Contains(c.Id));
            if (!adds.IsNull())
            {
                return datas.Add(adds);
            }
            return datas;
        }
        public void Delete (DBShopCouponGoods obj)
        {
            this._Repository.Delete(obj.Id);
        }
        public void Delete (long[] ids)
        {
            this._Repository.Delete(ids);
        }
        public DBShopCouponGoods Get (long id)
        {
            return this._Repository.Get(id);
        }

        public long[] GetSkuIds (long couponId)
        {
            return this._Repository.GetSkuIds(couponId);
        }
        public bool CheckIsExists (long couponId)
        {
            return this._Repository.IsExist(a => a.CouponId == couponId);
        }
        public DBShopCouponGoods[] Gets (long couponId)
        {
            return this._Repository.GetsByCouponId<DBShopCouponGoods>(couponId);
        }

        public void Clear (long couponId)
        {
            long[] ids = this._Repository.Gets(a => a.CouponId == couponId, a => a.Id);
            if (ids.IsNull())
            {
                return;
            }
            this._Repository.Delete(ids);
        }
    }
}
